//
//  VOLMenuViewController.m
//  Volver
//
//  Created by administrator on 14-9-15.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLMenuViewController.h"
#import "common.h"
#import "REFrostedViewController.h"
#import "UIViewController+REFrostedViewController.h"

#import "VOLAppDelegate.h"

#import "VOLSearchViewController.h"
#import "VOLSelectionViewController.h"
#import "VOLFavoriteViewController.h"
#import "VOLMyJourneyViewController.h"
#import "VOLHireViewController.h"
#import "VOLMyHouseViewController.h"
#import "VOLLoginViewController.h"
#import "VOLRegisterViewController.h"
#import "VOLHospitalityViewController.h"
#import "SetListViewController.h"
#import "VOLmyMesgViewController.h"


@interface VOLMenuViewController ()
{
    NSArray *menu;
    NSArray *haveLogin;
    NSArray *notLagin;
    VOLAppDelegate *del;
    
    NSFileManager *manager;
    
    int flag;
    
    //tableHeader视图
    UIImageView *headImageView;
    UILabel *userNameLabel;
}

@end

@implementation VOLMenuViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    del = kGetDel;
    
    flag = 0;
    
    //初始化数据
    menu = [NSArray array];
    //登录以的的菜单内容
    NSArray *haveLoginJourneyMenu = [NSMutableArray arrayWithObjects:@"搜索",@"精选",@"我的旅程",@"收藏夹",@"消息", nil];
    NSArray *haveLoginHireMenu = [NSMutableArray arrayWithObjects:@"出租主页",@"我的房源",@"好客之道", nil];
    NSDictionary *haveLoginDic1 = @{@"title": @"旅行",
                                    @"menu":haveLoginJourneyMenu};
    NSDictionary *haveLoginDic2 = @{@"title": @"出租",
                                    @"menu":haveLoginHireMenu};
    haveLogin = [NSMutableArray arrayWithObjects:haveLoginDic1,haveLoginDic2, nil];
    
    //未登录时的菜单内容
    NSArray *notLaginJourneyMenu = [NSMutableArray arrayWithObjects:@"搜索",@"精选", nil];
    NSArray *notLaginHireMenu = [NSMutableArray arrayWithObjects:@"好客之道", nil];
    NSDictionary *notLaginDic1 = @{@"title": @"旅行",
                                   @"menu":notLaginJourneyMenu};
    NSDictionary *notLaginDic2 = @{@"title": @"出租",
                                   @"menu":notLaginHireMenu};
    notLagin = [NSArray arrayWithObjects:notLaginDic1,notLaginDic2, nil];
    
    if (del.lastIndex == nil) {
        //默认在“精选”的位置
        del.lastIndex = [NSIndexPath indexPathForRow:1 inSection:0];
    }
    //去掉cell的分割线
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //初始化一些控件
#pragma mark - tableView的初始化
    //分隔符颜色
    self.tableView.separatorColor = [UIColor colorWithRed:150/255.0f green:161/255.0f blue:177/255.0f alpha:1.0f];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //透明
    self.tableView.opaque = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
#pragma mark - 头像
    //headerView
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 184.0f)];
    headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, 100, 100)];
    headImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
#pragma mark 添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToPersonalInfo:)];
    tapGesture.numberOfTouchesRequired = 1;
    tapGesture.numberOfTapsRequired = 1;
    [headerView addGestureRecognizer:tapGesture];
    //设置圆形
    headImageView.layer.masksToBounds = YES;
    headImageView.layer.cornerRadius = 50.0;
    headImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    headImageView.layer.borderWidth = 3.0f;
    headImageView.layer.rasterizationScale = [UIScreen mainScreen].scale;
    headImageView.layer.shouldRasterize = YES;
    headImageView.clipsToBounds = YES;
    
#pragma mark - 名字
    userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, 100, 24)];
    userNameLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:21];
    userNameLabel.backgroundColor = [UIColor clearColor];
    userNameLabel.textColor = [UIColor colorWithRed:62/255.0f green:68/255.0f blue:75/255.0f alpha:1.0f];
    userNameLabel.textAlignment = NSTextAlignmentCenter;
    //    [userNameLabel sizeToFit];
    userNameLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    
    //将头像和名字label加入到view中
    [headerView addSubview:headImageView];
    [headerView addSubview:userNameLabel];
    
#pragma mark - 设置tableHeader
    self.tableView.tableHeaderView = headerView;
    
#pragma mark - tableFooter
    self.tableView.tableFooterView = [[UILabel alloc] init];
}
#pragma mark 界面出现时加载内容
-(void)viewWillAppear:(BOOL)animated{
    
    
    [self initTableViewHeaderView];
    [self.tableView reloadData];
    
    //好客之道字体颜色控制
    if (del.isLogin) {
        //在登录前，进入的界面是“好客之道”时，在登录成功后，位置依然在“好客之道”
        if (del.lastIndex.section == 1 && del.lastIndex.row == 0 && flag == 0) {
            NSLog(@"改变cell的字体颜色");
            
            //上一个cell的字体颜色还原
            UITableViewCell *lastCell = [self.tableView cellForRowAtIndexPath:del.lastIndex];
            lastCell.textLabel.textColor = kMenuTextDefaultColor;
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
            //当前cell的字体变成主题色
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.textLabel.textColor = kThemeColor;
            
            //记录当前cell的indexPath
            del.lastIndex = indexPath;
            
        }
    }
}
#pragma mark 自定义tableView的头视图
-(void)initTableViewHeaderView{
    //判断菜单栏的内容
    if (del.isLogin) {
        menu = haveLogin;
    }else{
        menu = notLagin;
    }
    
#pragma mark - 判断显示头像的图片
    if (del.isLogin) {
        if ((NSNull *)del.currentUser.userHead != [NSNull null]) {
            //初始化manager
            manager = [NSFileManager defaultManager];
            //加载图片
            //先判断是否有这个路径存在，如果没有要先创建
            NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/userHead/%d",kGetDocumentsPath,del.currentUser.userID,del.currentUser.userID];
            if (![manager fileExistsAtPath:imageDocumentPath]) {
                [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            //先从本地查找是否已有图片
            NSString *imagePath = [NSString stringWithFormat:@"%@%d/userHead/%d/%@",kGetDocumentsPath,del.currentUser.userID,del.currentUser.userID,del.currentUser.userHead];
            if ([manager fileExistsAtPath:imagePath]) {
                headImageView.image = [UIImage imageWithContentsOfFile:imagePath];
            }
            else{
                //若不存在，调用方法下载图片
                [del loadHeadImage:del.currentUser.userHead userID:del.currentUser.userID headImageView:headImageView imagePath:imagePath];
            }
        }
        else{
            headImageView.image = [UIImage imageNamed:@"defaultHead.png"];
        }
    }
    else{
        headImageView.image = [UIImage imageNamed:@"clickLogin.png"];
    }
#pragma mark - 判断显示用户名字
    if (del.isLogin) {
        if (del.currentUser.userName != nil) {
            if ((NSNull *)del.currentUser.userName != [NSNull null]) {
                userNameLabel.text = del.currentUser.userName;
            }else{
                userNameLabel.text = @"暂无姓名";
            }
            
        }
        else
        {
            userNameLabel.text = @"暂无姓名";
        }
    }
    else{
        userNameLabel.text = @"未登录";
    }
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark 跳转个人信息界面
-(void)goToPersonalInfo:(UITapGestureRecognizer *)recognizer{
    //如果没有登录，跳转到登录界面
    if (!del.isLogin) {
        [self goToLogin];
    }else{
        //将del.lastIndex置为超过数组容量的一个位置
        del.lastIndex = [NSIndexPath indexPathForRow:10 inSection:10];
        
        NSLog(@"跳转个人信息界面");
        UINavigationController *navigationController = (UINavigationController *)self.frostedViewController.contentViewController;
        SetListViewController *setListView = [self.storyboard instantiateViewControllerWithIdentifier:@"setController"];
        navigationController.viewControllers = @[setListView];
        [self.frostedViewController hideMenuViewController];
        
    }
    
}

#pragma mark 跳转登录界面
-(void)goToLogin{
    VOLLoginViewController *loginvc = [self.storyboard instantiateViewControllerWithIdentifier:@"loginController"];
    [self presentViewController:loginvc animated:YES completion:^{
        
    }];
}



#pragma mark - UITableView Delegate

#pragma mark 自定义cell式样
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:17];
}

#pragma mark 自定义Section的Header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)sectionIndex
{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 34)];
    //    view.backgroundColor = [UIColor colorWithRed:167/255.0f green:167/255.0f blue:167/255.0f alpha:0.6f];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 8, 0, 0)];
    label.text = [menu[sectionIndex] objectForKey:@"title"];
    label.font = [UIFont systemFontOfSize:20];
    label.textColor = [UIColor colorWithRed:167/255.0f green:167/255.0f blue:167/255.0f alpha:1.0f];
    label.backgroundColor = [UIColor clearColor];
    [label sizeToFit];
    [view addSubview:label];
    
    return view;
}

#pragma mark SectionHeader的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectionIndex
{
    return 34;
}

#pragma mark 点击cell进行跳转界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //控制cell上字体颜色的变化
    if (!(indexPath.section == del.lastIndex.section && indexPath.row == del.lastIndex.row)) {
        //上一个cell的字体颜色还原
        UITableViewCell *lastCell = [self.tableView cellForRowAtIndexPath:del.lastIndex];
        lastCell.textLabel.textColor = kMenuTextDefaultColor;
        
        //当前cell的字体变成主题色
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.textColor = kThemeColor;
        
        //记录当前cell的indexPath
        del.lastIndex = indexPath;
    }
    
    
    UINavigationController *navigationController = (UINavigationController *)self.frostedViewController.contentViewController;
    
    
    if (indexPath.section == 0) {
        
        switch (indexPath.row) {
            case 0:
            {//这里的花括号不能省
                //搜索
                VOLSearchViewController *searchVC = [self.storyboard instantiateViewControllerWithIdentifier:@"searchViewController"];
                
                navigationController.viewControllers = @[searchVC];
            }
                break;
            case 1:
            {
                //精选
                VOLSelectionViewController *selection = [self.storyboard instantiateViewControllerWithIdentifier:@"selectionController"];
                del.isRefresh = 6;
                navigationController.viewControllers = @[selection];
            }
                break;
            case 2:
            {
                //我的旅程
                VOLMyJourneyViewController *myJourney = [self.storyboard instantiateViewControllerWithIdentifier:@"myJourneyController"];
                del.isRefresh = 4;
                navigationController.viewControllers = @[myJourney];
            }
                break;
            case 3:
            {
                //收藏夹
                VOLFavoriteViewController *favorite = [self.storyboard instantiateViewControllerWithIdentifier:@"favoriteViewController"];
                del.isRefresh = 3;
                navigationController.viewControllers = @[favorite];
            }
                break;
            case 4:
            {
                //我的消息
                VOLmyMesgViewController *message = [self.storyboard instantiateViewControllerWithIdentifier:@"volmyMesg"];
                //                del.isRefresh = 3;
                navigationController.viewControllers = @[message];
            }
                break;
                
        }
        
    }else{
        switch (indexPath.row) {
            case 0:
            {
                if (del.isLogin) {
                    VOLHireViewController *hire = [self.storyboard instantiateViewControllerWithIdentifier:@"hireController"];
                    del.isRefresh = 5;
                    navigationController.viewControllers = @[hire];
                    //flag置为1
                    flag = 1;
                }
                else{
                    VOLHospitalityViewController *hospitality = [self.storyboard instantiateViewControllerWithIdentifier:@"hospitalityController"];
                    navigationController.viewControllers = @[hospitality];
                    flag = 0;
                }
            }
                break;
            case 1:
            {
                VOLMyHouseViewController *myHouse = [self.storyboard instantiateViewControllerWithIdentifier:@"myHouseController"];
                del.isRefresh = 1;
                navigationController.viewControllers = @[myHouse];
            }
                break;
            case 2:
            {
                VOLHospitalityViewController *hospitality = [self.storyboard instantiateViewControllerWithIdentifier:@"hospitalityController"];
                navigationController.viewControllers = @[hospitality];
            }
                break;
        }
        
    }
    
    
    [self.frostedViewController hideMenuViewController];
}

#pragma mark - UITableView Datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return menu.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
    return [[menu[sectionIndex] objectForKey:@"menu"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    if (indexPath.section == del.lastIndex.section && indexPath.row == del.lastIndex.row) {
        cell.textLabel.textColor = kThemeColor;
    }else{
        cell.textLabel.textColor = kMenuTextDefaultColor;
    }
    
    
    
    NSArray *temp = [menu[indexPath.section] objectForKey:@"menu"];
    cell.textLabel.text = temp[indexPath.row];
    
    return cell;
}

#pragma mark 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}


@end
